<template>
  <div class="replenishment-list-wrap table-gl-w">
    <div class="search-w table-filter-form">
      <FilterTable ref="filterTable" :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #headerLeft>
          <a-space>
            <a-button type="primary" size="medium">设置变量规则</a-button>
            <a-button class="gray-outline" size="medium" @click="openAddPurchasePaln" v-if="$authPass('procurement.purchase.plan.save')">添加采购计划</a-button>
            <a-button class="gray-outline" size="medium" @click="openAddFBA" v-if="$authPass('procurement.fba.shipment.sale.save')">添加发货计划</a-button>
            <a-button class="gray-outline" size="medium" @click="refreshList" :loading="refreshLoading">刷新智能补货</a-button>
            <div>
              <span>已选</span>
              <span class="highlight" style="margin-left: 10px">{{ selectIds.length }}</span>
            </div>
            <a-button type="text" size="medium" @click="clearSelect">清除已选</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table
            class="table-two-line"
            ref="tableRef"
            row-key="id"
            :loading="tableLoading"
            @selection-change="selectColumn"
            :row-selection="rowSelection"
            :data="tableList"
            @sorter-change="sorterChange"
            :scroll="{
              x: 1800,
              y: '100%',
            }"
            size="mini"
            :bordered="{ headerCell: true }"
            :pagination="false"
          >
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="shop" title="站点/店铺" :width="120" fixed="left">
                <template #cell="{ record }">
                  <p style="color: #ccc">{{ $extract(marketPlaceList[record.marketplaceId], 'name') }}</p>
                  <TextLimit :rows="1">{{ record.shopName }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column data-index="img" title="图片" :width="60" fixed="left">
                <template #cell="{ record }">
                  <ImgPopover :src="getMainUrl(record)">
                    <template #con>
                      <a-image width="40" height="40" fit="contain" :src="getMainUrl(record)" />
                    </template>
                  </ImgPopover>
                </template>
              </a-table-column>
              <a-table-column data-index="productName" title="产品名称" :width="140" fixed="left">
                <template #cell="{ record }">
                  <TextLimit :rows="2">{{ record.productName }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column data-index="sku" title="SKU/品类" :width="130" fixed="left">
                <template #cell="{ record }">
                  <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="1" />
                  <p>{{ record.cateName || '--' }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="msku" title="MSKU/ASIN" :width="130" fixed="left">
                <template #cell="{ record }">
                  <TextLimit :rows="1">{{ record.msku || '--' }}</TextLimit>
                  <TextLimit :rows="1">{{ record.asin || '--' }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column title="销售员" :width="70" fixed="left">
                <template #cell="{ record }">
                  <p>{{ getSalesmans(record) }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="productLevel" title="商品等级" :width="70" />
              <a-table-column title="FBA库存">
                <a-table-column data-index="amtFba" title="可用库存" :width="85" :sortable="sortable" />
                <a-table-column data-index="amtOnWayFba" title="在途库存" :width="85" :sortable="sortable" />
              </a-table-column>
              <a-table-column title="国内仓库存">
                <a-table-column data-index="amtDomestic" title="可用库存" :width="85" :sortable="sortable">
                  <template #cell="{ record }">
                    <div class="flex-c-sb">
                      <p>{{ record.amtDomestic }}</p>
                      <a-tooltip position="top" content="库存调拨">
                        <i class="icon icon-tiaoboruku cursor" @click="openTransferDialog(record)"></i>
                      </a-tooltip>
                    </div>
                  </template>
                </a-table-column>
                <a-table-column data-index="amtOnWayDomestic" title="在途库存" :width="85" :sortable="sortable" />
              </a-table-column>
              <a-table-column title="海外仓库存">
                <a-table-column data-index="amtAbroad" title="可用库存" :width="85" :sortable="sortable" />
                <a-table-column data-index="amtOnWayAbroad" title="在途库存" :width="85" :sortable="sortable" />
              </a-table-column>
              <a-table-column title="采购数">
                <a-table-column data-index="amtPurchasePlan" title="计划中" :width="85" :sortable="sortable" />
                <a-table-column data-index="amtPurchasing" title="采购中" :width="85" :sortable="sortable" />
              </a-table-column>
              <a-table-column data-index="salesVolume7" title="7天日均销量" :width="80" :sortable="sortable" />
              <a-table-column data-index="salesVolume15" title="15天日均销量" :width="80" :sortable="sortable" />
              <a-table-column data-index="salesVolume30" title="30天日均销量" :width="80" :sortable="sortable" />
              <a-table-column data-index="salesVolume" title="日均消耗量" :width="80" :sortable="sortable" />
              <a-table-column data-index="targetAmtDay" title="目标库存天数" :width="80" :sortable="sortable" />
              <a-table-column data-index="targetAmtTime" title="目标库存日期" :width="120" :sortable="sortable">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.targetAmtTime, 'YYYY/MM/DD') }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="targetAmt" title="目标库存量" :width="80" :sortable="sortable" />
              <a-table-column data-index="outStockDate" title="缺货日期" :width="120" :sortable="sortable">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.outStockDate, 'YYYY/MM/DD') }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="recommendPurchaseDate" title="建议采购日期" :width="120" :sortable="sortable">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.recommendPurchaseDate, 'YYYY/MM/DD') }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="amtPurchaseRecommend" title="推荐采购量" :width="80" :sortable="sortable" />
              <a-table-column data-index="amtFbaRecommend" title="推荐FBA发货量" :width="80" :sortable="sortable" />
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 添加FBA货件 -->
  <AddAndEditFba v-if="showEditFbaDialog" :defaultList="fbaList" source="replenishment" :isShow="showEditFbaDialog" @closed="showEditFbaDialog = false" @success="getTableList" />
  <!-- 库存调拨 -->
  <StockTransfer v-if="showTransferDialog" :isShow="showTransferDialog" :currentItem="currentData" @closed="showTransferDialog = false" @success="getTableList" />
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { FilterTableItem } from '@/types/components'
  import { findReplenishPage, refreshReplenish } from '@/api/purchase'
  import TableWrap from '@/components/TableWrap.vue'
  import { Message } from '@arco-design/web-vue'
  import { useRouter } from 'vue-router'
  import { marketPlaceList } from '@/utils/globalData'
  import useBaseDataStore from '@/store/modules/base-data'
  import AddAndEditFba from '@/views/purchase/fbaManagement/components/addAndEditFba.vue'
  import StockTransfer from './components/stockTransfer.vue'
  onMounted(async () => {
    getTableList()
    getMarketList()
    getShopList()
    getUserList()
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any

  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'marketplaceIds',
      label: '站点',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'shopIds',
      label: '全部店铺',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
      attrs: {
        isCorrelation: true,
        correlationKey: 'marketplaceId',
      },
    },
    {
      type: 'input_keyword_type',
      key: 'sku',
      keyItems: [
        { label: 'SKU', value: 'sku' },
        { label: '产品名称', value: 'productName' },
        { label: 'MSKU', value: 'msku' },
        { label: 'ASIN', value: 'asin' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 180,
      isMultiple: true,
    },
    {
      key: 'productLevel',
      label: '商品等级',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [
        {
          label: 'A',
          value: 'A',
        },
        {
          label: 'B',
          value: 'B',
        },
        {
          label: 'C',
          value: 'C',
        },
        {
          label: 'D',
          value: 'D',
        },
      ],
    },
    {
      key: 'salesmanId',
      label: '销售员',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      type: 'keyword_date_range',
      key: 'outStockDate',
      keyItems: [
        { label: '缺货日期', value: 'outStockDate' },
        { label: '最迟发货日期', value: 'latestSendDate' },
        { label: '建议采购日期', value: 'recommendPurchaseDate' },
      ],
      keyWidth: '130',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])

  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const sortable: any = ref({
    sortDirections: ['descend', 'ascend'],
    sorter: true,
  })
  const total = ref(0)
  const tableLoading = ref(false)
  const showEditFbaDialog = ref(false)
  const tableList = ref<Array<any>>([])
  const selectIds = ref([])
  const selectRows = ref([])
  const fbaList = ref([])

  const tableRef = ref()
  const router = useRouter()
  const filterData = ref<any>({})
  const useBaseData = useBaseDataStore()
  const filterTable = ref()
  const tableListMap = ref({})
  const currentData = ref<any>({})
  const showTransferDialog = ref(false)
  const refreshLoading = ref(false)

  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    let optionItems = useBaseData.userList?.map((el: any) => {
      return {
        label: el.userName,
        value: el.id,
      }
    })
    filterTable.value.changeOptions(4, optionItems)
  }
  // 获取站点
  async function getMarketList() {
    await useBaseData.getMarketList()
    let optionItems = useBaseData.markedtList.map((el: any) => {
      return {
        label: el.marketplaceName,
        value: el.marketplaceId,
      }
    })
    filterTable.value.changeOptions(0, optionItems)
  }
  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopListAndShare()
    let optionItems = useBaseData.shopListAndShare.map((el: any) => {
      return {
        label: el.shopName,
        value: el.sellerMarketId,
      }
    })
    filterTable.value.changeOptions(1, optionItems)
  }
  // 根据站点过滤店铺店铺
  async function filterShopList(marketplaceIds: Array<string>) {
    let list = useBaseData.shopListAndShare.filter((el: any) => !marketplaceIds.length || marketplaceIds.includes(el.marketplaceId))
    let optionItems = list.map((el: any) => {
      return {
        label: el.shopName,
        value: el.sellerMarketId,
        id: el.id,
      }
    })
    filterTable.value.changeOptions(1, optionItems)
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  // 清除选中
  function clearSelect() {
    tableRef.value.selectAll(false)
  }
  // 通过查询
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    if (info.marketplaceIds != filterData.value.marketplaceIds) {
      filterShopList(info.marketplaceIds ? info.marketplaceIds.split(',') : [])
    }
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 获取商品列表
  async function getTableList() {
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    clearSelect()
    const res: any = await findReplenishPage(params)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    tableListMap.value = {}
    tableList.value.forEach((el) => {
      tableListMap.value[el.id] = el
    })
  }
  // 排序
  function sorterChange(dataIndex: string, direction: string) {
    searchVal.value.sortField = dataIndex
    searchVal.value.sortType = direction == 'ascend' ? 1 : -1
    getTableList()
  }
  // 显示图片
  function getMainUrl(row: any) {
    return row?.productImgs?.[0]
  }
  // 显示业务员
  function getSalesmans(row: any) {
    return row?.salesmans?.[0]?.salesmanName
  }
  // 添加采购计划
  function openAddPurchasePaln() {
    if (!selectIds.value.length) {
      Message.error('请选择商品')
      return
    }
    window.localStorage.setItem('addPurchasePalnIds', selectIds.value.join(','))
    router.push('/purchase/purchaseManagement/addPurchasePlan?addModel=replenishment')
  }
  // 刷新智能补货
  async function refreshList() {
    if (!selectIds.value.length) {
      Message.error('请选择商品')
      return
    }
    refreshLoading.value = true
    const res: any = await refreshReplenish({ ids: selectIds.value })
    refreshLoading.value = false
    if (res) {
      Message.success('刷新成功')
      getTableList()
    }
  }
  // 添加发货计划
  function openAddFBA() {
    if (!selectIds.value.length) {
      Message.error('请选择商品')
      return
    }
    // 共享店铺产品不能添加FBA
    getSelectRows()
    fbaList.value = selectRows.value.filter((el: any) => !el.share)
    if (!fbaList.value.length) {
      Message.error('请选择非共享店铺商品')
      return
    }
    showEditFbaDialog.value = true
  }
  function getSelectRows() {
    selectRows.value = []
    selectIds.value.map((id) => {
      selectRows.value.push(tableListMap.value[id])
    })
  }
  // 打开库存调拨
  function openTransferDialog(row: any) {
    currentData.value = row
    showTransferDialog.value = true
  }
</script>
<style lang="less" scoped>
  :deep(.arco-table-sorter) {
    margin-left: 2px;
  }
</style>
